<template>
    <div class="dept-view">
        <el-row style="margin-bottom:12px;" align="middle">
            <el-col :span="24" style="text-align:right;">
                <el-button type="primary" @click="fetchDepts">刷新</el-button>
            </el-col>
        </el-row>

        <el-table :data="depts" v-loading="loading" element-loading-text="加载中..." style="width:100%">
            <el-table-column prop="children.deptName" label="部门名称" min-width="180">
                <template #default="{ row }">
                    <span>{{ row.children?.deptName || row.deptName }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="deptName" label="上级部门" min-width="160" />
            <el-table-column prop="createdAt" label="创建时间" min-width="180">
                <template #default="{ row }">
                    <span>{{ formatDate(row.createdAt) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
                <template #default="{ row }">
                    <el-button type="text" size="small">编辑</el-button>
                    <el-button type="text" size="small" style="color:#f56c6c">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElRow, ElCol, ElButton, ElTable, ElTableColumn } from 'element-plus'

const API_DEPT = 'http://localhost:5216/api/SystemManagement/Departmentshow'

const loading = ref(false)
const depts = ref([])

function formatDate(value) {
    if (!value) return ''
    return new Date(value).toLocaleString()
}

async function fetchDepts() {
    loading.value = true
    try {
        const res = await axios.get(API_DEPT)
        const payload = res.data || res
        if (payload && payload.data) {
            depts.value = payload.data.items || payload.data || []
        } else if (Array.isArray(payload)) {
            depts.value = payload
        } else if (payload.items) {
            depts.value = payload.items
        } else {
            depts.value = []
        }
    } catch (err) {
        console.error('fetchDepts error', err)
    } finally {
        loading.value = false
    }
}

onMounted(() => fetchDepts())
</script>

<style scoped>
.dept-view {
    padding: 12px
}
</style>
